<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    <canvas width="300" height="300" id="canvas"></canvas>

    <!-- <script>
      let canvas = document.querySelector("#canvas");
      let context = canvas.getContext("2d");

      //   context.beginPath();
      //   context.moveTo(150, 150);

      //   context.arc(150, 150, 100, (Math.PI / 180) * 0, (Math.PI / 180) * 90);

      //   //   闭合路径
      //   context.closePath();
      //   context.stroke();

      const drawDot = ({ x, y }) => {
        context.beginPath();
        context.arc(x, y, 10, 0, 2 * Math.PI);
        context.fillStyle = "red";
        context.fill();
      };

      var x = 150;
      var y = 150;
      var speedX = -1;
      var speedY = 0.1;

      setInterval(() => {
        //   删除矩形
        context.clearRect(0, 0, 300, 300);

        x += speedX;
        y += speedY;
        if (x >= 290 || x <= 10) {
          speedX = -speedX;
        }
        drawDot({ x, y });
      }, 1000 / 60);
    </script> -->

    <script>
      let canvas = document.querySelector("#canvas");
      let context = canvas.getContext("2d");

      const drawDot = ({ x, y, color }) => {
        context.beginPath();
        context.arc(x, y, 10, 0, 2 * Math.PI);
        context.fillStyle = color;
        context.fill();
      };

      const updateDotPos = (dot) => {
        dot.x += dot.speedX;
        dot.y += dot.speedY;

        if (dot.x >= 290 || dot.x <= 10) {
          dot.speedX = -dot.speedX;
        }
      };

      var dot1 = {
        x: 150,
        y: 150,
        speedX: -1,
        speedY: 0.1,
        color: "red",
      };

      var dot2 = {
        x: 100,
        y: 100,
        speedX: -1,
        speedY: -0.1,
        color: "green",
      };
      //   var x = 150;
      //   var y = 150;
      //   var speedX = -1;
      //   var speedY = 0.1;

      setInterval(() => {
        //   删除矩形
        context.clearRect(0, 0, 300, 300);
        updateDotPos(dot1);
        updateDotPos(dot2);
        drawDot(dot1);
        drawDot(dot2);
      }, 1000 / 60);
    </script>
  </body>
</html>
